#include <stdio.h>
#include <winscard.h>

int main(int argv, char** argc)
{
	int j;
	char key;
	SCARDCONTEXT	hSC;
	LONG			lReturn, lReturn2;
	// Establish the context.
	lReturn = SCardEstablishContext(SCARD_SCOPE_USER,
									NULL,
									NULL,
									&hSC);
	if ( SCARD_S_SUCCESS != lReturn )
	{
		printf("Failed SCardEstablishContext!\n");
		printf("No card found in your system! Press enter to exit....");
		scanf("%c", &key);
		return 0;
	}
	else
	{
		printf("Establish Context! trying to get reader name...\n");
		LPTSTR          pmszReaderGroups = NULL;
		LPTSTR          pReaderGroup;
		DWORD           cch = SCARD_AUTOALLOCATE;
		// Retrieve the list the reader groups.
		// hSC was set by a previous call to SCardEstablishContext.
		lReturn = SCardListReaderGroups(hSC, 
										(LPTSTR)&pmszReaderGroups,
										&cch );
		if ( SCARD_S_SUCCESS != lReturn )
			printf("Failed SCardListReaderGroups\n");
		else
		{
			printf("Query ListReaderGroups, Len=%d\n", cch);
			for(j=0;j<cch;j++)
				printf("%c",*(pmszReaderGroups+j));
			printf("\n");

			lReturn = SCardFreeMemory(hSC, pmszReaderGroups);
			if ( SCARD_S_SUCCESS != lReturn )
				printf("Failed SCardFreeMemory\n");

			LPTSTR			pmszReaders = NULL;
			LPTSTR          pReader;
			cch = SCARD_AUTOALLOCATE;
			lReturn = SCardListReaders( hSC,
									    NULL,
									   (LPTSTR)&pmszReaders,
									    &cch );
			printf("listReader Len=%d, %s\n", cch, pmszReaders);
			for(j=0;j<cch;j++)
				printf("%c",*(pmszReaders+j));
			printf("\n");
			switch( lReturn )
			{
			case SCARD_E_NO_READERS_AVAILABLE:
				printf("Reader is not in groups.\n");
				// Take appropriate action.
				// ...
				break;
			
			case SCARD_S_SUCCESS:
				// Do something with the multi string of readers.
				// Output the values.
				// A double-null terminates the list of values.
				pReader = pmszReaders;
				while ( '\0' != *pReader )
				{
					// Display the value.
					printf("Reader: %S\n", pReader );
					// Advance to the next value.
					pReader = pReader + strlen((char*)pReader) + 1;
				}
				// Free the memory.
				lReturn2 = SCardFreeMemory( hSC,
											pmszReaders );
				if ( SCARD_S_SUCCESS != lReturn2 )
					printf("Failed SCardFreeMemory\n");
				break;

			default:
				printf("Failed SCardListReaders\n");
				// Take appropriate action.
				// ...
				break;
			}

		}


		// Use the context as needed. When done,
		// ...

		lReturn = SCardReleaseContext(hSC);
		if ( SCARD_S_SUCCESS != lReturn )
		{
			printf("Failed SCardReleaseContext\n");
			return 0;
		}
    
	}

	printf("hello\n");
	int i;
	scanf("%d",&i);
}